package com.scujj.cs6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.cs6.common.BusinessException;
import com.scujj.cs6.common.ErrorCode;
import com.scujj.cs6.mapper.AnswerMapper;
import com.scujj.cs6.model.dto.answer.AnswerDTO;
import com.scujj.cs6.model.entity.*;
import com.scujj.cs6.model.vo.AnswerVo;
import com.scujj.cs6.model.vo.MyAnswerVo;
import com.scujj.cs6.model.vo.PageVo;
import com.scujj.cs6.service.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author FlanChan
 * @description 针对表【answer】的数据库操作Service实现
 * @createDate 2025-03-25 21:21:24
 */
@Service
@AllArgsConstructor
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer>
        implements AnswerService {

    private final QuestionService questionService;

    @Override
    public PageVo<AnswerVo> getAnswers(int page , int size, Long questionId) {
        List<AnswerVo> answerVos = this.baseMapper.pageAnswerVoById(questionId, (page - 1) * size, size);
        int total = (int) this.count(new LambdaQueryWrapper<Answer>().eq(Answer::getQuestionId, questionId));
        PageVo<AnswerVo> pageVo = new PageVo<>();
        pageVo.setRecords(answerVos);
        pageVo.setTotal(total);
        pageVo.setSize(size);
        pageVo.setPage(page);
        pageVo.setTotalPage((total + size - 1) / size);
        return pageVo;
    }

    @Override
    public PageVo<MyAnswerVo> getMyAnswers(int page, int size, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");

        // 计算分页偏移量
        int offset = (page - 1) * size;

        List<MyAnswerVo> answers = this.baseMapper.getMyAnswers(userId, offset, size);

        // 查询总记录数
        int total = this.baseMapper.countMyAnswers(userId);

        // 计算总页数
        int totalPage = (total + size - 1) / size;

        // 返回分页对象
        return new PageVo<>(page, size, totalPage, total, answers);
    }

    @Override
    public PageVo<AnswerVo> getFollowedAnswers(int page, int size, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");

        // 计算分页偏移量
        int offset = (page - 1) * size;

        // 获取当前用户关注的用户的回答
        List<AnswerVo> answers = this.baseMapper.selectFollowedAnswers(userId, offset, size);

        // 查询总数量
        int total = this.baseMapper.countFollowedAnswers(userId);

        // 计算总页数
        int totalPage = (total + size - 1) / size;

        // 返回分页对象
        return new PageVo<>(page, size, totalPage, total, answers);
    }

    @Override
    public void createAnswer(Long id, AnswerDTO answer, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");

        Question q = questionService.getById(id);
        if (q == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND,"问题不存在");
        }
        if (q.getUserId().equals(userId)) {
            throw new BusinessException(ErrorCode.FORBIDDEN,"无法回答自己的问题");
        }

        Answer newAnswer = new Answer(answer);
        newAnswer.setQuestionId(id);
        newAnswer.setUserId(userId);
        this.save(newAnswer);
    }

    @Override
    public void updateAnswer(Long id, AnswerDTO answer, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        Answer ans = this.getById(id);
        if (ans == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND,"回答不存在");
        }
        if (!Objects.equals(ans.getUserId(), userId)) {
            throw new BusinessException(ErrorCode.FORBIDDEN,"无权限修改");
        }
        BeanUtils.copyProperties(answer, ans);
        ans.setUpdateTime(new Date());
        this.updateById(ans);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteAnswer(Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        Answer answer = this.getById(id);
        if (!Objects.equals(answer.getUserId(), userId)) {
            throw new BusinessException(ErrorCode.FORBIDDEN,"无权限删除");
        }
        this.baseMapper.deleteAnswerById(id);
    }

    @Override
    public void updateLikeCount(Long id, int i) {
        Answer answer = this.getById(id);
        if (answer == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND,"回答不存在");
        }
        answer.setLikeCount(answer.getLikeCount() + i);
        this.updateById(answer);
    }
}




